package com.android.systemui.statusbar.board;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.widget.ImageView;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.util.Log;

/**
 * Created by drolmen on 2017/8/30.
 * 长按时会多次回调OnClickListener
 */
public class LongPressImageView extends ImageView {

    public static final int DELAY_MILLIS = 50;
    private static final int ARGS = 1212;
    private GestureDetector mGestureDetector;

    private boolean mCanceled;   //标识是否需要处理触摸事件
    private OnClickListener mOnClickListener;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == ARGS && !mCanceled && mOnClickListener != null) {
                mHandler.sendEmptyMessageDelayed(ARGS, DELAY_MILLIS);
                mOnClickListener.onClick(LongPressImageView.this);
            }
        }
    };

    public LongPressImageView(Context context) {
        super(context);
        init(context);
    }

    public LongPressImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isClickable()) {
            return false;
        }
        if (mOnClickListener != null) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mCanceled = false;
                mOnClickListener.onClick(this);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                mHandler.removeCallbacksAndMessages(null);
            }
        }
        return mGestureDetector.onTouchEvent(event);
    }

    private void init(Context context) {
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {

            @Override
            public void onLongPress(MotionEvent e) {
                super.onLongPress(e);
                mHandler.sendEmptyMessageDelayed(ARGS, DELAY_MILLIS);
            }

            @Override
            public boolean onDown(MotionEvent e) {
                return true;
            }
        });
    }

    @Override
    public void setOnClickListener(@Nullable OnClickListener l) {
        super.setOnClickListener(l);
        mOnClickListener = l;
    }

    /**
     * 取消此次操作
     */
    public void cancel() {
        mCanceled = true;
        mHandler.removeMessages(ARGS);
    }

}
